// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
  traceUser: true
}) // 使用当前云环境

const db = cloud.database();
const Collection = db.collection("user_subscribe")
/**
 * 链接数据库
 */
const ConnectDB = () => {
  return new Promise(async (resolve) => {
    const tempDb = await db.collection("user_subscribe")
    resolve(tempDb)
  })
}
/**
 * 成功的响应
 */
const successFun = (data) => {
  return {
    ...data,
    code: 200
  }
}

/**
 * 失败的响应
 * @param {} msg 
 * @param {*} code 
 */
const errFun = (params = {}) => {
  return {
    msg: '系统错误',
    code: -1,
    ...params
  }
}

// 日期格式化函数
function formatDate(d) {
  const date = new Date(d.getTime() + 28800)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

/**
 * 提交预约信息
 */
const addSubscriben = async (params) => {
  const {
    phone = '', name = '', OPENID = '', car_number = '', freight_type = '', img_path = ''
  } = params
  if (!phone || !name || !car_number || !freight_type || !img_path) return errFun({
    msg: '参数错误'
  })
  const subDB = await db.collection("user_subscribe")
  // 查询库中是否存在
  const queryResult = await subDB.where({
    phone,
  }).get()
  // 调用生成订单号的云函数
  const orderResult = await cloud.callFunction({
    name: 'generateOrderNumber'
  })

  // 检查订单号生成是否成功
  if (orderResult.result.code === 'FUNCTIONS_EXECUTE_FAIL') {
    return {
      code: 'ORDER_NUMBER_FAIL',
      message: '生成订单号失败',
      detail: orderResult.result.detail
    }
  }

  const orderNumber = orderResult.result.orderNumber

  if (queryResult.data.length > 0) {
    // 更新数据
    if (queryResult.data.length > 1) {
      //查询时间最近的一条数据
      const item = queryResult.data.sort((a, b) => b.create_time - a.create_time)
      // 查询多余的数据
      const filterList = queryResult.data.filter(i => i._id !== item._id)
      // 需要删除filterList里这些数据
      const deleteOperations = filterList.map(i => subDB.doc(i._id).remove())
      await Promise.all(deleteOperations)
      await subDB.doc(item._id).update({
        data: {
          name,
          phone,
          car_number,
          freight_type,
          orderNumber,
          img_path,
          create_time: new Date(), // 服务器时间
          status: 1
        }
      })
    } else {
      const item = queryResult.data[0]
      await subDB.doc(item._id).update({
        data: {
          name,
          phone,
          car_number,
          freight_type,
          orderNumber,
          img_path,
          create_time: new Date(),
          status: 1
        }
      })
    }
  } else {
    // 新建数据
    await subDB.add({
      data: {
        phone,
        name,
        car_number,
        freight_type,
        orderNumber,
        img_path,
        create_time: new Date(),
        openid: OPENID,
        status: 1
      },
    })
  }
  return successFun({
    msg: '操作成功'
  })
}
/**
 * 获取列表
 * @param {*} params 
 */
const getSubScribeList = async (params) => {
  const queryResult = await db.collection("user_subscribe").where({
      openid: params.OPENID,
    }).field({
      name: true,
      phone: true,
      car_number: true,
      freight_type: true,
      status: true,
      img_path: true,
      orderNumber: true,
      create_time: true
    })
    .orderBy('create_time', 'desc')
    .get()
  const resultData = queryResult.data.map(item => {
    return {
      ...item,
      create_time: item.create_time ? new Date(item.create_time).getTime() : ''
    }
  })
  return successFun({
    data: resultData || [],
    message: '操作成功'
  })
}
/**
 * 获取全部列表
 */
const getAllSubScribeList = async () => {
  const MAX_LIMIT = 100
  try {
    // 1. 获取status=1的总记录数
    const countResult = await Collection.where({
      // status: 1
    }).count()
    const total = countResult.total
    if (total === 0) {
      return successFun({
        data: [],
        total: 0,
        message: '没有符合条件的记录'
      })
    }
    // 3. 计算需要分多少批次获取
    const batchTimes = Math.ceil(total / MAX_LIMIT)
    // 4. 并行获取所有批次数据
    const tasks = []
    for (let i = 0; i < batchTimes; i++) {
      const promise = Collection.where({
          // status: 1
        })
        .field({
          name: true,
          phone: true,
          car_number: true,
          freight_type: true,
          status: true,
          img_path: true,
          orderNumber: true,
          create_time: true
        })
        .orderBy('create_time', 'desc') // 按创建时间倒序
        .skip(i * MAX_LIMIT)
        .limit(MAX_LIMIT)
        .get()
      tasks.push(promise)
    }
    // 5. 等待所有查询完成并合并结果
    const results = await Promise.all(tasks)
    const data = results.reduce((acc, cur) => {
      return [...acc, ...(cur.data || [])]
    }, [])
    const resultData = data.map(item => {
      return {
        ...item,
        create_time: item.create_time ? new Date(item.create_time).getTime() : ''
      }
    })
    return successFun({
      data: resultData || [],
      total: data.length,
      message: '操作成功'
    })
  } catch (err) {
    console.error('云函数错误:', err)
    return errFun({
      msg: '获取失败：' + err.message
    })
  }
}
/**
 * 修改叫号状态
 */
const updateStatus = async (params) => {
  if (!params.id) return errFun({
    msg: 'id错误'
  })
  await Collection.doc(params.id).update({
    data: {
      status: 2
    }
  })
  return successFun({
    msg: '操作成功'
  })
}
/**
 * 获取用户手机号
 */
const getUserPhone = async (params) => {
  if (!params.code) return errFun({
    msg: '参数错误'
  })
  try {
    const res = await cloud.openapi.phonenumber.getPhoneNumber({
      openid: params.OPENID,
      code: params.code
    })
    return successFun({
      msg: '操作成功',
      data: res?.phoneInfo || ""
    })
  } catch (err) {
    return errFun({
      msg: '解析失败:' + err,
    })
  }
}

// 云函数入口函数
exports.main = async ({
  type = '',
  params = {}
}, context) => {
  try {
    // 获取微信上下文
    const wxContext = cloud.getWXContext();
    // 验证 openid 是否存在
    if (!wxContext.OPENID) {
      return errFun({
        msg: '未获取到用户OPENID',
      });
    }
    const {
      OPENID,
      APPID,
      UNIONID = null
    } = wxContext
    switch (type) {
      case "addSubscriben":
        return await addSubscriben({
          OPENID,
          ...params
        });
      case "getSubScribeList":
        return await getSubScribeList({
          OPENID,
          ...params
        });
      case "getAllSubScribeList":
        return await getAllSubScribeList({
          OPENID,
          ...params
        });
      case "updateStatus":
        return await updateStatus({
          OPENID,
          ...params
        });
      case "getUserPhone":
        return await getUserPhone({
          OPENID,
          ...params
        });
    }
  } catch (err) {
    return errFun({
      msg: 'userSubscribeFun Error：' + err,
    })
  }
}